﻿using Newtonsoft.Json;
using System;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;
using System.Reflection;
using System.Data;

namespace Help
{
    public class ObjectSerialize
    {
        #region 将对象返回Json或Xml
        /// 对象序列化成 XML String  
        /// </summary>  
        public string XmlSerialize<T>(T obj)
        {
            string xmlString = string.Empty;
            XmlSerializer xmlSerializer = new XmlSerializer(typeof(T));
            XmlSerializerNamespaces xn = new XmlSerializerNamespaces();
            xn.Add("", "");
            StringBuilder sb = new StringBuilder();
            XmlWriterSettings xs = new XmlWriterSettings();
            xs.Encoding = Encoding.UTF8;
            xs.OmitXmlDeclaration = false;
            xs.Indent = true;
            try
            {
                XmlWriter xw = XmlWriter.Create(sb, xs);
                xmlSerializer.Serialize(xw, obj, xn);
                xmlString = sb.ToString();
                // xmlString = Encoding.UTF8.GetString(ms.ToArray());
            }
            catch (Exception)
            {

            }
            return xmlString;
        }


        ///  对象序列化成 Json String
        /// </summary>
        /// <typeparam Name="T"></typeparam>
        /// <param Name="obj"></param>
        /// <returns></returns>
        public string JsonSerialize<T>(T obj)
        {
            string res = string.Empty;
            try
            {
                JsonSerializerSettings settings = new JsonSerializerSettings();
                settings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                string result = JsonConvert.SerializeObject(obj, settings);
                return result;
            }
            catch (Exception)
            {

                throw;
            }
        }


        /// 将对象返回Json或Xml
        /// </summary>
        /// <typeparam Name="T"></typeparam>
        /// <param Name="obj"></param>
        /// <param Name="RETID"></param>
        /// <returns></returns>
        public string StringOfObject<T>(T obj, int RETID)
        {
            string res = string.Empty;
            try
            {
                switch (RETID)
                {
                    case 1:
                        res = JsonSerialize(obj);
                        break;
                    case 2:
                        res = XmlSerialize(obj);
                        break;
                    default:
                        break;
                }
                return res;
            }
            catch (Exception)
            {

                throw;
            }
        }
        #endregion
    }

    #region 把字串转类
    public static class ParseClass<T> where T : class,new()
    {

        public static List<T> JsonList(IList<JToken> jieguo)
        {
            List<T> ls = new List<T>();

            Type tp = typeof(T);
            PropertyInfo[] pr = tp.GetProperties();
            for (int i = 0; i < jieguo.Count; i++)
            {
                T cl = new T();
                foreach (PropertyInfo item in pr)
                {
                    object bb = null;
                    switch (item.PropertyType.Name.ToString())
                    {
                        case "Int32":
                            bb = (int)jieguo[i][item.Name];
                            break;
                        case "String":
                            bb = (string)jieguo[i][item.Name];
                            break;
                        default:
                            break;
                    }

                    item.SetValue(cl, bb, null);
                }
                ls.Add(cl);
            }
            return ls;
        }

        public static T JsonToClass(string str_class)
        {
            T cl = new T();
            Type tp = typeof(T);
            JObject jb = JObject.Parse(str_class);
            PropertyInfo[] pr = tp.GetProperties();
            foreach (PropertyInfo item in pr)
            {
                object bb = null;
                try
                {
                    switch (item.PropertyType.Name.ToString())
                    {
                        case "Int32":
                            bb = (int)jb[item.Name];
                            break;
                        case "String":
                            bb = (string)jb[item.Name];
                            break;
                        default:
                            if (item.PropertyType.FullName.ToString().Contains("Int"))
                            {
                                bb = (int)jb[item.Name];
                            }
                            else
                            {
                                bb = (string)jb[item.Name];
                            }
                            break;
                    }
                }
                catch (Exception)
                {
                     
                }
              
                item.SetValue(cl, bb, null);
            }
            return cl;
        }
        /// <summary>
        /// 将字符串转换成实体类
        /// </summary>
        /// <param name="Str">字符串</param>
        /// <param name="RETID">字符串类型（1：JSON；2：XML）</param>
        /// <returns></returns>
        public static T StrDeserialize(string Str, int RETID)
        {
            switch (RETID)
            {
                case 1:
                    return JsonDeserialize(Str);
                default:
                    return XMLDeserialize(Str);
            }
        }
        /// <summary>
        ///把字条串转成类
        /// </summary>
        /// <param name="XML"></param>
        /// <returns></returns>
        public static T XMLDeserialize(string XML)
        {
            try
            {
                T 类 = default(T);
                XmlSerializer xer = new XmlSerializer(typeof(T));
                XmlTextReader reader = new XmlTextReader(new StringReader(XML));
                类 = (T)xer.Deserialize(reader);
                return 类;
            }
            catch (Exception ex)
            {
                WriteLog.WriteW("解析用户的更新操作的数据出现异常：" + ex.Message);
                return default(T);
            }
        }

        public static T JsonDeserialize(string json)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            T obj = default(T);
            using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
            {
                obj = (T)serializer.ReadObject(ms);
                ms.Close();
            }
            return obj;
        }

        /// <summary>
        /// 入参DataRow返回一个有数据的实体类
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        public static T ReturnClass(DataRow dr)
        {

            T cl = new T();
            Type classtype = typeof(T);
            PropertyInfo[] pr = classtype.GetProperties();
            foreach (PropertyInfo item in pr)
            {
                if (dr.Table.Columns.Contains(item.Name))
                {
                    try
                    {

                        item.SetValue(cl, dr[item.Name], null);
                    }
                    catch (Exception)
                    {

                    }
                }
            }
            return cl;
        }
        /// <summary>
        /// 入参DATATABLE返回泛型类
        /// </summary>
        /// <param name="tb">DataTable</param>
        /// <returns></returns>
        public static List<T> ReturnList(DataTable tb)
        {
            List<T> ls = new List<T>();
            for (int i = 0; i < tb.Rows.Count; i++)
            {
                T cl = ReturnClass(tb.Rows[i]);
                ls.Add(cl);
            }
            return ls;
        }
    }
    #endregion


}
